<template>
  <div class="app-container">
    <el-row :gutter="20" class="div-height-left">
      <el-col :span="24" :xs="24" class="div-height-left">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>入库主记录（点击列表可查看入库药品明细）</span>
              </div>
              <div class="mb20">
                <el-form v-show="showSearch" ref="queryParamsRef" :inline="true"
                         :model="queryParams" label-width="100px">
                  <el-form-item v-if="!userInfo.orgId">
                    <select-org-tree :value="queryParams.orgId" @orgNodeClick="orgNodeClick"/>
                  </el-form-item>
                  <el-form-item label="入库类别" prop="importClass">
                    <el-select v-model="queryParams.importClass" class="width-120" clearable
                               placeholder="请选择入库类别">
                      <el-option v-for="dict in dictDataMap['drug_storage_type']"
                                 :key="dict.dictValue" :label="dict.dictLabel"
                                 :value="dict.dictValue"/>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="入库单号" prop="documentNo">
                    <el-input v-model="queryParams.documentNo" clearable placeholder="请输入入库单号"
                              @keyup.enter.native="handleQuery"/>
                  </el-form-item>
                  <el-form-item label="库存单位" prop="storageId">
                    <drug-storage-info ref="storageIdDeptRef" :clearable="false"
                                       :org-id="queryParams.orgId"
                                       :value="queryParams.storageId" :value-storage-id="queryParams.storageId"
                                       class="import-master" style="width: 180px"
                                       @drugStorageChange="storageIdClick"/>
                  </el-form-item>
                  <el-form-item label="入库日期" prop="importDate">
                    <el-date-picker v-model="dateRange" :unlink-panels="true" end-placeholder="结束日期"
                                    range-separator="截止"
                                    start-placeholder="开始日期" style="width: 320px;" type="daterange"
                                    @change="timeChange"></el-date-picker>
                  </el-form-item>
                  <div class="mr20 mb5" style="float: right">
                    <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
                  </div>
                </el-form>
                <el-table v-adaptive :border="true" :data="drugImportMasterList" :header-cell-style="$headerCellStyle"
                          :stripe="true" highlight-current-row @row-click="masterClick">
                  <!--            <el-table-column type="selection" width="55" :align="'center'"/>-->
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库类别"
                                   min-width="70px" prop="importClass">
                    <template #default="scope">
                      <dict-data-tag :options="dictDataMap['drug_storage_type']"
                                     :value="scope.row.importClass"/>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库单号"
                                   min-width="120px" prop="documentNo" width=""/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="采购商"
                                   prop="supplierName"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库库房"
                                   prop="storageName"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="出库库房"
                                   prop="storageFromName"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库日期"
                                   prop="importDate" width="100">
                    <template #default="scope">
                      <span>{{ $parseTime(scope.row.importDate, "{y}-{m}-{d}") }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'left'" :show-overflow-tooltip="true" label="操作人"
                                   prop="createByName" width="60px"/>
                  <el-table-column :align="'left'" :show-overflow-tooltip="true" label="已付款(元)"
                                   min-width="95px" prop="accountPayed">
                    <template #default="scope">
                      {{ parseFloat(scope.row.accountPayed).toFixed(2) }}
                    </template>
                  </el-table-column>
                  <!--                                    <el-table-column :show-overflow-tooltip="true" label="备注信息" :align="'center'"-->
                  <!--                                                     prop="remarks"/>-->
                  <el-table-column :align="'left'" class-name="small-padding fixed-width" fixed="right"
                                   label="操作" width="50">
                    <template #default="scope">
                      <el-tooltip class="item" content="打印" effect="dark" placement="top">
                        <el-button circle type="primary" @click="drugImportPrint(scope.row)">
                          <template #icon>
                            <i-ep-printer/>
                          </template>
                        </el-button>
                      </el-tooltip>

                    </template>
                  </el-table-column>
                </el-table>
                <pagination v-show="total > 0" v-model:limit="queryParams.pageSize"
                            v-model:page="queryParams.pageNum" :total="total" @pagination="getList"/>
              </div>
            </el-card>
          </el-col>
          <el-col :span="16">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>入库单明细</span>
              </div>
              <div class="mb20">
                <el-table v-adaptive :border="true" :data="stagingListDetail"
                          :header-cell-style="$headerCellStyle">
                  <el-table-column :align="'center'" label="药品编号" min-width="100px" prop="drugCode"/>
                  <el-table-column :align="'center'" label="药品名称" min-width="130px" prop="drugName"/>
                  <el-table-column :align="'center'" label="包装数量" min-width="90px"
                                   prop="packageNum"/>
                  <el-table-column :align="'center'" label="包装规格" min-width="120px"
                                   prop="packageSpec">
                    <template #default="scope">
                      {{ scope.row.packSize === '2' ? scope.row.packageSpec : scope.row.minSpec }}
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="入库数量" min-width="90px" prop="quantity">
                    <template #default="scope">
                      <div>
                        <dict-data-tag v-if="scope.row.packSize === '2'"
                                       :options="dictDataMap['spec_unit']" :value="scope.row.packageUnits"
                                       class="mb-10 mr10" style="float: right"/>
                        <dict-data-tag v-else :options="dictDataMap['spec_unit']"
                                       :value="scope.row.minUnits" class="mb-10 mr10"
                                       style="float: right"/>
                        <div class="mr20" style="float: right; font-weight: bold">
                          {{
                            scope.row.quantity
                          }}
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="进货价(元)" min-width="90px"
                                   prop="tradePrice">
                    <template #default="scope">
                      {{
                        scope.row.packSize === '2' ? scope.row.tradePrice :
                          scope.row.tradePriceMin
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="零售价(元)" min-width="90px"
                                   prop="retailPrice">
                    <template #default="scope">
                      {{
                        scope.row.packSize === '2' ? scope.row.retailPrice :
                          scope.row.retailPriceMin
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="生产批号" min-width="90px" prop="batchNo"/>
                  <el-table-column :align="'center'" label="生产日期" min-width="90px" prop="produceDate">
                    <template #default="scope">
                      <span>{{ $parseTime(scope.row.produceDate, "{y}-{m}-{d}") }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="有效期" min-width="90px" prop="expireDate">
                    <template #default="scope">
                      <span>{{ $parseTime(scope.row.expireDate, "{y}-{m}-{d}") }}</span>
                    </template>
                  </el-table-column>
                </el-table>
                <pagination v-show="detailTotal > 0" v-model:limit="detailQuery.pageSize"
                            v-model:page="detailQuery.pageNum" :total="detailTotal"
                            @pagination="getListDetail"/>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import {getDrugImportMaster, selectPageDrugImportMaster,} from "@/api/drug/drugImportMaster";
import {selectPageDrugImportDetail} from "@/api/drug/drugImportDetail";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";

const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any;
const dictStore = useDictStoreHook();
const dictDataMap = ref(
  dictStore.isTypeGetData("drug_storage_type", "drug_payment_type", "spec_unit")
);
const currentSelectDept = proxy.$currentSelectDept
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const storageIdDeptRef = ref();
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);
// 选中数组
const ids = ref([]);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 明细
const detailTotal = ref(0);
// 药品入库主表表格数据
const drugImportMasterList = ref<any>([]);
const stagingListDetail = ref<any>([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 查询参数
const queryParamsRef = ref();
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  documentNo: undefined,
  storageId: currentSelectDept,
  importDate: undefined,
  supplier: undefined,
  storageFrom: undefined,
  accountReceivable: undefined,
  accountPayed: undefined,
  additionalFee: undefined,
  importClass: undefined,
  accountType: undefined,
  accountIndicator: undefined,
  acctDate: undefined,
  acctOperator: undefined,
  tally: undefined,
  tallyDate: undefined,
  tallyOperator: undefined,
  orgId: undefined,
  voucherNo: undefined,
  recoveryDocuNo: undefined,
  isStaging: "N",
});
// 明细列表查询参数
const detailQuery = ref({
  pageNum: 1,
  pageSize: 10,
  masterId: "",
});

if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId;
  getList();
}

// 机构树点击事件
function orgNodeClick(data, _e) {
  queryParams.value.orgId = data.orgId;
  if (queryParams.value.orgId) {
    getList();
  }
}

/** 查询药品入库主表列表 */
function getList() {
  if (!queryParams.value.orgId) {
    return ElMessage.error(proxy.$OrgIdIsEmpty);
  }
  selectPageDrugImportMaster(proxy.$addDateRange(queryParams.value, dateRange.value)).then((response: any) => {
    drugImportMasterList.value = response.rows;
    total.value = response.total;
    stagingListDetail.value = []
  });
}


function timeChange(e) {
  if (e) {
    dateRange.value = [proxy.$parseTime(e[0], "{y}-{m}-{d} 00:00:00"), proxy.$parseTime(e[1], "{y}-{m}-{d} 23:59:59")]
  }
  getList()
}

async function masterClick(row) {
  detailQuery.value.masterId = row.id;
  await getListDetail();
}

/** 查询入库单明细 */
async function getListDetail() {
  await selectPageDrugImportDetail(detailQuery.value).then((response: any) => {
    stagingListDetail.value = response.rows;
    detailTotal.value = response.total;
  });
  return stagingListDetail.value;
}

function storageIdClick(obj) {
  queryParams.value.storageId = obj.storageId;
  getList();
}

// 取消按钮
function cancel() {
  open.value = false;
  // reset();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields();
  storageIdDeptRef.value.setValue("");
  handleQuery();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  // reset();
  const id = row.id || ids.value;
  getDrugImportMaster(id).then(() => {
    // form.value = response.data;
    open.value = true;
    title.value = "修改药品入库主表";
  });
}

/** 提交按钮 */
// function submitForm() {
//     $refs["form"].validate(valid => {
//         if (valid) {
//             buttonLoading.value = true;
//             if (form.value.id != null) {
//                 updateDrugImportMaster(form.value).then(() => {
//                     ElMessage.success("修改成功");
//                     open.value = false;
//                     getList();
//                 }).finally(() => {
//                     buttonLoading.value = false;
//                 });
//             } else {
//                 addDrugImportMaster(form).then(() => {
//                     ElMessage.success("新增成功");
//                     open.value = false;
//                     getList();
//                 }).finally(() => {
//                     buttonLoading.value = false;
//                 });
//             }
//         }
//     });
// }
/** 导出按钮操作 */
function handleExport() {
  // download('drug/drugImportMaster/export', {
  //     ...queryParams
  // }, `drugImportMaster_${new Date().getTime()}.xlsx`)
}

/**
 * 入库单打印
 * @param row
 */
function drugImportPrint(row: any) {
  let url = "/drug/drugImportMaster/drugImportPrint";
  const formData = new FormData()
  formData.append("importId", row.id)
  formData.append("orgId", row.orgId)
  // pdf打印 、打印预览
  proxy.$printPdfPublic(url, formData).then(res => {
    if (res) {
      // nextTick(() => {
      // printPreviewRef.value.init(objectUrl.value)
      // })
    } else {
      console.error('处方打印失败')
    }
  })
}

onMounted(() => {
  if (proxy.$currentSelectDept) {
    nextTick(() => {
      storageIdDeptRef.value.getDrugStorageList()
    })
  }
})

</script>

<script lang="ts">
export default {
  name: "MasterRecord",
};
</script>
